package de.bbl.android.tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.util.ByteArrayBuffer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import de.bbl.android.classes.RssItem;

public class XmlParseRssTools {
	
	public static RssItem[] XmlParseRss(String xmlFilename, String tempDirectory) {		
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	try {
    		DocumentBuilder db = dbf.newDocumentBuilder();
    		Document dom = db.parse(new File(xmlFilename));
    		Element docElement = dom.getDocumentElement();
    		NodeList nl = docElement.getElementsByTagName("item");

    		return XmlParseRssItems(nl, tempDirectory);    		
    		
    	} catch (Exception e) {
        	Tools.AppendToErrorFile(e.getMessage());
            // e.printStackTrace();
    	}
		return null;
	}
	
	private static RssItem[] XmlParseRssItems(NodeList nl, String tempDirectory) {
		int itemCount = nl.getLength();
		RssItem[] retVal = new RssItem[itemCount];
		for (int i = 0; i < itemCount; i++) {
			Node currentItem = nl.item(i);
			String title = "";
			String description = "";
			String link = "";
			String pubdate = "";
			String guid = "";
			
			// hier sind wir im Item
			int childNodeCount = currentItem.getChildNodes().getLength();
			ArrayList<String> array = new ArrayList<String>();
			
			for (int j = 0; j < childNodeCount; j++) {
				Node currentChildNode = currentItem.getChildNodes().item(j);
				String tempNodeName = currentChildNode.getNodeName().toLowerCase();
				if (tempNodeName.equals("title")) {
					title = currentChildNode.getTextContent();
				} else if (tempNodeName.equals("description")) {
					description = currentChildNode.getTextContent();
				} else if (tempNodeName.equals("link")) {
					link = currentChildNode.getTextContent();
				} else if (tempNodeName.equals("pubdate")) {
					pubdate = currentChildNode.getTextContent();
				} else if (tempNodeName.equals("guid")) {
					guid = currentChildNode.getTextContent();
				} else if (tempNodeName.equals("enclosure")) {
					NamedNodeMap nnm = currentChildNode.getAttributes();
					Node tempImageNode = nnm.getNamedItem("url");
					array.add(tempImageNode.getTextContent());
				}				
			}
			
			retVal[i] = new RssItem(title, description, link, guid, pubdate);
			String[] imgStore = array.toArray(new String[1]);
			// if (imgStore.length == 0)
			//     imgStore = null;
			// String[] imgStore = storeImages(array, tempDirectory);
			retVal[i].setImagePath(imgStore);
		}
		return retVal;
	}
	
	@SuppressWarnings("unused")
	private static String[] storeImages(ArrayList<String> imagesToStore, String storeDirectory) {
		
		if (imagesToStore.size() == 0)
			return null;
		
		String[] retval = new String[imagesToStore.size()];
		
		for (int i = 0; i <imagesToStore.size(); i++)
		{
			try {
			    String tempUrl = imagesToStore.get(i);
	            URL url = new URL(tempUrl); 
	            String filename = storeDirectory + tempUrl.substring(tempUrl.lastIndexOf("/") + 1 );
	            File file = new File(filename);
	            retval[i] = filename;
	            
	            if (new File(filename).exists()) {
	            	continue;
	            }
	
	            // long startTime = System.currentTimeMillis();
	            /* Open a connection to that URL. */
	            URLConnection ucon = url.openConnection();
	
	            /*
	             * Define InputStreams to read from the URLConnection.
	             */
	            InputStream is = ucon.getInputStream();
	            BufferedInputStream bis = new BufferedInputStream(is);
	
	            /*
	             * Read bytes to the Buffer until there is nothing more to read(-1).
	             */
	            ByteArrayBuffer baf = new ByteArrayBuffer(50);
	            int current = 0;
	            while ((current = bis.read()) != -1) {
	                    baf.append((byte) current);
	            }
	
	            /* Convert the Bytes read to a String. */
	            FileOutputStream fos = new FileOutputStream(file);
	            fos.write(baf.toByteArray());
	            fos.close();
			} catch (IOException e) {
	        	Tools.AppendToErrorFile(e.getMessage());
	            // e.printStackTrace();
			}
		}
		return retval;
	}
}
